package com.qys.training.server.controller;

import com.qys.training.base.dto.BaseResult;
import com.qys.training.base.exception.QysException;
import com.qys.training.biz.auth.entity.User;
import com.qys.training.biz.auth.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    /**
     * 新建用户
     *
     * @param user 用户名&密码
     * @return 状态
     */
    @PostMapping(path = "/create")
    public BaseResult create(User user) {
        //username password非空校验
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return BaseResult.error("用户名或密码不能为空");
        }
        try { //插入成功反会返回主键
            Long id = this.userService.create(user);
            return BaseResult.success(id);
        } catch (QysException e) {
            //username重复
            return BaseResult.error("该用户已存在");
        }
    }

    /**
     * 用户名密码验证
     * @param user
     * @return
     */
    @PostMapping("/proving")
    public BaseResult proving(User user) {
        //username password非空校验
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return BaseResult.error("用户名或密码不能为空");
        }
        User proving = userService.proving(user);
        if (proving != null) {
            return BaseResult.success("用户名和密码正确");
        } else {
            return BaseResult.error("用户名和密码错误");
        }
    }


    @PostMapping(path = "/testQysException")
    public @ResponseBody
    BaseResult testQysException() {
        this.userService.testQysException();
        return BaseResult.success();
    }

    @PostMapping(path = "/testOtherException")
    public @ResponseBody
    BaseResult testOtherException() {
        this.userService.testOtherException();
        return BaseResult.success();
    }

}
